package com.yunhe.common.util;

import java.text.DecimalFormat;
import java.util.regex.Pattern;

public class NumberUtil {
    private static Pattern intPattern;
    private static Pattern numberPattern;

    /**
     * double类型四舍五入
     * @param value 原数据
     * @param digit 保留位数
     * @return
     */
    public static Double round(Double value, int digit) {
        if (digit > 0) {
            StringBuilder pattern = new StringBuilder("#.");
            for (int i = 0; i < digit; i++) {
                pattern.append("0");
            }
            DecimalFormat df = new DecimalFormat(pattern.toString());
            String format = df.format(value);
            return Double.parseDouble(format);
        } else {
            return value;
        }
    }

    /**
     * 判断是否是整数
     * @param str 字符串
     * @return 是整数返回true,否则返回false
     */
    public static boolean isInteger(String str) {
        if (intPattern == null) {
            intPattern = Pattern.compile("^[-\\+]?[\\d]*$");
        }
        return intPattern.matcher(str).matches();
    }

    /**
     * 判断是否是数字
     * @param str 字符串
     * @return 是数字返回true,否则返回false
     */
    public static boolean isNumber(String str) {
        if (numberPattern == null) {
            numberPattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
        }
        return numberPattern.matcher(str).matches();
    }
}
